#pragma once
#include <iostream>
#include <string>
#include <chrono>
#include <sstream>
#include <unistd.h>
#include <memory>
#include<fstream>
#include<filesystem>
#include "Mutex.hpp"

enum class LogLevel
{
    DEBUG,
    INFO,
    WARNING,
    ERROR,
    FATAL
};

std::string LevelToString(LogLevel level)
{
    switch (level)
    {
    case LogLevel::DEBUG:
        return "debug";
    case LogLevel::INFO:
        return "info";
    case LogLevel::WARNING:
        return "warning";
    case LogLevel::ERROR:
        return "error";
    case LogLevel::FATAL:
        return "fatal";
    default:
        return "unknown";
    }
}

class SyncStrategy
{
public:
    virtual ~SyncStrategy() = default;
    virtual void SyncLog(const std::string &message) = 0;
};

class ConsaleSyncStrategy
{
public:
    void SyncLog(const std::string &message)
    {
        {
            LockGuard lockguard(&_lock);
            std::cout << message.c_str() << std::endl;
        }
    }
    ~ConsaleSyncStrategy() {}

private:
    Mutex _lock;
};

const std::string path="log";
const std::string file="text.txt";

class FileSyncStrategy
{
public:
    FileSyncStrategy(const std::string&pathname=path,const std::string&filename=file)
        :_pathname(pathname),_filename(filename)
    {
        {
            LockGuard lockguard(&_lock);
            if (std::filesystem::exists(_pathname))
            {
                return;
            }
            try
            {
                std::filesystem::create_directories(_pathname);
            }
            catch (const std::filesystem::filesystem_error &e)
            {
                std::cerr << e.what() << "\r\n";
            }
        }
    }
    void SyncLog(const std::string &message)
    {
        {
            LockGuard lockguard(&_lock);
            std::string target = _pathname;
            target += "/";
            target += _filename;

            std::ofstream out(target.c_str(), std::ios::app);
            if (!out.is_open())
            {
                return;
            }
            out << message << "\n";
            out.close();
        }
    }
    ~FileSyncStrategy(){}
private:
    std::string _pathname;
    std::string _filename;
    Mutex _lock;
};

std::string GetTime()
{
    auto now = std::chrono::system_clock::now();
    std::time_t now_time = std::chrono::system_clock::to_time_t(now);
    std::tm *local_time = std::localtime(&now_time);
    char timebuffer[64];
    std::strftime(timebuffer, sizeof(timebuffer), "%Y-%M-%d %H:%M:%S", local_time);
    return timebuffer;
}

class Logger
{
public:
    Logger() {}
    void EnableFileSyncStrategy()
    {
        _ptr=std::make_unique<FileSyncStrategy>();
    }
    void EnableConsaleSyncStrategy()
    {
        _ptr=std::make_unique<ConsaleSyncStrategy>();
    }
    class LogMessage
    {
    public:
        LogMessage(LogLevel level, const std::string &file, int line, Logger &logger)
            : _time(GetTime()), _level(level), _pid(getpid()), _file(file), _line(line), _logger(logger)
        {
            std::stringstream ss;
            ss << "[" << _time << "] [" << LevelToString(_level) << "] [" << _pid << "] [" << _file << "] [" << _line << "]" << " - ";
            _message += ss.str();
        }
        template <typename T>
        LogMessage &operator<<(const T &info)
        {
            std::stringstream ss;
            ss += info;
            _message += ss;
            return *this;
        }
        ~LogMessage()
        {
            if (_logger._ptr)
            {
                _logger._ptr->SyncLog(_message);
            }
        };

    private:
        // 【时间】【等级】【pid】【文件名】【行号】【信息】
        std::string _time;
        LogLevel _level;
        pid_t _pid;
        std::string _file;
        int _line;
        std::string _message;
        Logger &_logger;
    };
    LogMessage operator()(LogLevel level, const std::string &file, int line)
    {
        return LogMessage(level, file, line, *this);
    }
    ~Logger()
    {
    }

private:
    std::unique_ptr<SyncStrategy> _ptr;
};

Logger logger;

#define LOG(level) logger(level, __FILE__, __LINE__)
#define EnableFileSyncStrategy() logger.EnableFileSyncStrategy()
#define EnableConsaleSyncStrategy() logger.EnableConsaleSyncStrategy()